package images

import (
	"context"
	"server/internal/common/biz"

	"server/internal/svc"
	"server/internal/types"
	"server/internal/utils"

	"github.com/docker/docker/api/types/image"
	"github.com/zeromicro/go-zero/core/logx"
)

type PullLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// pull image
func NewPullLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PullLogic {
	return &PullLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PullLogic) Pull(req *types.PullImageReq, respChan chan string, errChan chan *biz.Error) {
	out, err := l.svcCtx.DockerCli.ImagePull(context.TODO(), req.RepoTag, image.PullOptions{})
	if err != nil {
		l.Logger.Errorf("pull image error:%s", err.Error())
		errChan <- biz.ImagePullError
		return
	}
	defer out.Close()
	utils.ReadCloserToStringAsync(out, respChan)
}
